<template>
  <div class="header-pc-wrap">
    <!-- 登录框 开始-->
    <el-dialog title="登录" v-model="dialogFormVisible" width="400">
      <!-- 登录表单 -->
      <div id="loginForm" style="display: block">
        <el-form :model="formLabelAlign" label-position="top" class="demo-form-inline">
          <el-form-item label="手机号">
            <el-input v-model="username" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input type="password" v-model="password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="login" style="width: 100%">登录</el-button>
          </el-form-item>
        </el-form>
        <img @click="goToLoginWX" src="/images/wxlogin.png" alt="" />
      </div>
      <!-- 二维码 -->
      <div id="wxLoginForm" style="display: none">
        <h2>微信登录</h2>
        <img src="/images/wxlogin.png">
      </div>
    </el-dialog>
    <!-- 登录框 结束-->
    <!-- 顶部登录条 -->
    <div class="wrap-box">
      <div @click="toToIndex" class="edu-icon"></div>
      <div @click="toToIndex" class="text">泡泡教育</div>
      <div class="right-var-wrap" v-if="!isLogin">
        <div class="login-handler" @click="goToLogin">登录 | 注册</div>
      </div>
      <div class="right-var-wrap" v-if="isLogin">
        <div :class="{ 'tip-icon': true, 'has-new-message': isHasNewMessage }">
          <i class="el-icon-bell"></i>
        </div>
        <img :src="user.icon || (user.content && user.content.icon)" class="avatar-wrap" />
        <div class="bar-wrap">
          <ul class="account-bar">
            <li class="user_dropdown" data-lg-tj-track-code="index_user">
              <span class="unick">{{ user.realname || (user.content && user.content.realname) }}</span>
              <i />
              <ul style="">
                <li @click="goToSetting">
                  账号设置
                </li>
                <li @click="logout">
                  退出
                </li>
              </ul>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import qs from 'qs'
import { ElMessage } from 'element-plus'

export default {
  name: "Header",
  props: {},
  setup() {
    const isLogin = ref(false) // 登录状态，true：已登录，false：未登录
    const user = ref(null) // 用来保存登录的用户信息
    const isHasNewMessage = ref(false) // 是否有新的推送消息
    const dialogFormVisible = ref(false) // 是否显示登录框，true：显示，false：隐藏
    const username = ref("student") // 双向绑定表单 手机号
    const password = ref("123") // 双向绑定表单 密码

    // 组件挂载时检查登录状态
    onMounted(() => {
      const storedUser = localStorage.getItem('user')
      let token = localStorage.getItem('access-token')

      // 如果access-token不存在，尝试获取token
      if (!token) {
        token = localStorage.getItem('token')
      }

      console.log('Header.vue onMounted - 用户信息:', storedUser)
      console.log('Header.vue onMounted - token:', token)

      if (storedUser && token) {
        try {
          user.value = JSON.parse(storedUser)
          console.log('Header.vue - 解析后的用户信息:', user.value)

          // 确保用户信息正确显示
          if (user.value && user.value.content) {
            console.log('Header.vue - 用户信息是嵌套结构')
          } else if (user.value) {
            console.log('Header.vue - 用户信息是非嵌套结构')
          } else {
            console.log('Header.vue - 用户信息无效')
          }

          isLogin.value = true

          // 确保两个token键名都存储了相同的值
          localStorage.setItem('access-token', token)
          localStorage.setItem('token', token)

          // 可选：验证token是否有效
          axios.get('/user/checkToken', {
            headers: {
              'Authorization': `Bearer ${token}`
            }
          })
            .then(response => {
              console.log('Token验证成功:', response.data)
            })
            .catch(error => {
              console.error('Token验证失败:', error)
              if (error.response && error.response.status === 401) {
                // token无效，清除登录状态
                localStorage.removeItem('user')
                localStorage.removeItem('access-token')
                isLogin.value = false
                user.value = null
              }
            })
        } catch (e) {
          console.error('解析用户信息失败', e)
          localStorage.removeItem('user')
          localStorage.removeItem('access-token')
        }
      }
    })

    const goToSetting = () => {
      window.location.href = "/setting"; // 跳转个人设置页面
    }

    const goToLogin = () => {
      dialogFormVisible.value = true; // 显示登录框
    }

    const login = () => { // 前去登录
      // 前去登录
      axios.post('http://localhost:9000/login', qs.stringify({ 'username': username.value, 'password': password.value }), {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })
        .then(res => {
          console.log('login response:', res.data)
          // 检查返回的数据结构
          if (res.data && (res.data.statusCodeValue === 200 || res.data.statusCode === "OK") && res.data.body) {
            ElMessage.success('登录成功')
            user.value = res.data.body.user
            isLogin.value = true

            // 存储用户信息和token
            console.log('存储用户信息:', res.data.body.user)
            console.log('存储token:', res.data.body.token)
            localStorage.setItem('user', JSON.stringify(res.data.body.user))
            localStorage.setItem('token', res.data.body.token)
            localStorage.setItem('access-token', res.data.body.token)

            dialogFormVisible.value = false
            // 刷新页面以应用新的登录状态
            // window.location.reload()
          } else {
            ElMessage.error(res.data?.message || '登录失败')
          }
        })
        .catch(error => {
          console.error('登录错误:', error)
          ElMessage.error('登录失败: ' + (error.response?.data?.message || '服务器错误'))
        })
    }

    // 微信登录
    const goToLoginWX = () => {
      // 普通的登录表单隐藏
      document.getElementById("loginForm").style.display = "none";
      // 显示二维码的容器
      document.getElementById("wxLoginForm").style.display = "block";
      // 到后台获得微信登录参数
      var count = 0;
      var timer = window.setInterval(() => {
        count++;
        if (count == 3) {
          alert('登录成功')
          dialogFormVisible.value = false;
          isLogin.value = true;
          user.value = { nickname: '百里半', icon: '/images/course/oracle1.jpg' };
          document.getElementById("loginForm").style.display = "block";
          document.getElementById("wxLoginForm").style.display = "none";
          window.clearInterval(timer);
        }
      }, 2000);
    }

    const toToIndex = () => {
      window.location.href = "/"; //回到首页
    }

    //登出
    const logout = () => {
      axios.post('/logout')
        .then(res => {
          localStorage.removeItem('user')
          localStorage.removeItem('access-token')
          isLogin.value = false
          ElMessage.success('已成功退出登录')
        })
        .catch(error => {
          console.error('登出错误:', error)
          // 即使后端请求失败，也清除本地存储
          localStorage.removeItem('user')
          localStorage.removeItem('access-token')
          isLogin.value = false
          ElMessage.success('已退出登录')
        })
    }

    return {
      isLogin,
      user,
      isHasNewMessage,
      dialogFormVisible,
      username,
      password,
      goToSetting,
      goToLogin,
      login,
      goToLoginWX,
      toToIndex,
      logout
    }
  }
};
</script>

<style lang="less" scoped>
.header-pc-wrap {
  width: 100%;
  height: 40px;
  background: rgba(35, 39, 43, 1);
}

.wrap-box {
  width: 1200px;
  height: 100%;
  margin: 0 auto;
}

.edu-icon {
  float: left;
  width: 24px;
  height: 24px;
  background: url("/images/Icon@2x.png") no-repeat;
  background-size: 100% 100%;
  margin-top: 8px;
}

.text {
  font-size: 16px;
  font-weight: 500;
  color: rgba(255, 255, 255, 1);
  line-height: 40px;
  float: left;
  margin-left: 6px;
}

.login-handler {
  font-size: 12px;
  font-weight: 500;
  color: rgba(255, 255, 255, 1);
  line-height: 40px;
  float: left;
  cursor: pointer;
}

.right-var-wrap {
  float: right;
  font-size: 0;
  text-align: right;
}

.tip-icon,
.avatar-wrap,
.bar-wrap {
  display: inline-block;
  vertical-align: top;
}

.tip-icon {
  font-size: 16px;
  line-height: 40px;
  margin-right: 26px;
  color: #818895;
  cursor: pointer;

  &:hover {
    color: #fff;
  }

  &.has-new-message {
    position: relative;

    &:after {
      content: " ";
      display: inline-block;
      position: absolute;
      top: 50%;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background: red;
      right: 0;
      margin-top: -7px;
    }
  }
}

.user_dropdown {

  position: relative;
  cursor: pointer;
  font-size: 14px;
  text-align: center;

  &:hover {
    .unick {
      color: #fff;
    }

    i {
      -webkit-transform: rotate(180deg);
      -moz-transform: rotate(180deg);
      -ms-transform: rotate(180deg);
      -o-transform: rotate(180deg);
      transform: rotate(180deg);
      animation-fill-mode: forwards;
      border-color: #fff transparent transparent;
    }

    >ul {
      display: block;
      position: absolute;
      width: 110px;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      background: #fff;
      left: -40px;
      line-height: 45px;
      color: #666;
      font-size: 14px;
      z-index: 10;

      &:before {
        content: '';
        width: 0;
        height: 0;
        position: absolute;
        left: 50%;
        top: -21px;
        transform: translate(-50%);
        border: 11px solid transparent;
        border-bottom-color: #fff;
      }

      >li {
        line-height: 40px;
        height: 40px;
        overflow: hidden;

        &:hover {
          color: rgba(0, 53, 114, 1);
          background: rgba(0, 116, 250, 0.1);
        }
      }
    }
  }

  i {
    display: inline-block;
    position: relative;
    top: -1px;
    width: 0;
    height: 0;
    border: 4px solid;
    border-color: #818895 transparent transparent;
    margin-left: 4px;
    transition: all 0.3s ease-in-out;
  }

  >ul {
    display: none;
  }

  .unick {
    display: inline-block;
    vertical-align: middle;
    color: #818895;
    overflow: hidden;
    max-width: 175px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.account-bar {
  font-size: 12px;
  font-weight: 500;
  color: rgba(255, 255, 255, 1);
  line-height: 40px;
  float: left;
  cursor: pointer;
}

.avatar-wrap {
  width: 26px;
  height: 26px;
  border-radius: 50%;
  margin-right: 8px;
  margin-top: 7px;
}

#loginForm img {
  width: 30px;
  margin-left: 220px;
  cursor: pointer;
}

#wxLoginForm {
  text-align: center;
}

#wxLoginForm img {
  width: 100px;
}
</style>
